package com.hkbigdata.sink;

import com.hkbigdata.entry.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.List;

/**
 * @author liuanbo
 * @creat 2023-04-26-17:05
 * @see 2194550857@qq.com
 */
public class Flink02_Sink_Custom {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        List<WaterSensor> waterSensors = Arrays.asList(
                new WaterSensor("ws_001", 1607527992000L, 20),
                new WaterSensor("ws_001", 1607527992001L, 22),
                new WaterSensor("ws_001", 1607527992002L, 33),
                new WaterSensor("ws_002", 1607527992003L, 44),
                new WaterSensor("ws_002", 1607527992004L, 22),
                new WaterSensor("ws_002", 1607527992001L, 50)
        );

        env.fromCollection(waterSensors)
                .addSink(new RichSinkFunction<WaterSensor>() {
                    private Connection connection;
                    PreparedStatement preparedStatement;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/test?useSSL=false", "root", "123456");
                        preparedStatement = connection.prepareStatement("insert into sensor values (?,?,?)");
                    }

                    @Override
                    public void close() throws Exception {
                        connection.close();
                        preparedStatement.close();
                    }

                    @Override
                    public void invoke(WaterSensor value, Context context) throws Exception {
                        preparedStatement.setString(1,value.getId());
                        preparedStatement.setLong(2,value.getTs());
                        preparedStatement.setInt(3,value.getVc());
                        preparedStatement.execute();
                    }
                });

        env.execute();
    }
}
